package com.star.spring.easyexcel.utils;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import jakarta.servlet.http.HttpServletResponse;

import com.alibaba.excel.EasyExcel;
import com.star.spring.easyexcel.listener.ImageExcelListener;

import org.springframework.web.multipart.MultipartFile;

public class ExcelUtil {


    public static <T> List<T> readExcel(MultipartFile file, Class<T> clazz) {
        try {
            InputStream inputStream = file.getInputStream();
            return EasyExcel.read(inputStream).head(clazz).sheet().doReadSync();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


    public static <T> List<T> readExcelWithImages(MultipartFile file, Class<T> clazz, String imageSavePath) {
        try {
            ImageExcelListener<T> listener = new ImageExcelListener<>(imageSavePath);
            InputStream inputStream = file.getInputStream();
            EasyExcel.read(inputStream, clazz, listener)
                    .sheet()
                    .doRead();
            return listener.getDataList();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static <T> void writeExcel(List<T> list, Class exportDTOClass, HttpServletResponse response) {

        response.reset();
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-disposition",
                "attachment;filename=user_excel_" + System.currentTimeMillis() + ".xlsx");

        try {
            EasyExcel.write(response.getOutputStream(), exportDTOClass).sheet("sheet1").doWrite(list);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }


    }

}
